<template>
  <div
    v-loading="loading"
    class="h-full overflow-y-auto overflow-x-hidden w-[968px] mt-4 -translate-x-1 pb-1"
  >
    <div v-show="!noData" ref="pageContainer" class="relative"></div>
    <div
      class="h-full w-[960px] translate-x-1 border-base rounded-xl after:rounded-xl flex justify-center items-center bg-white"
      v-show="noData"
    >
      暂无数据
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, createApp, nextTick, onMounted } from 'vue'
import { getCustomeRender } from '@/views/briefinfo/services/chat-api'
import { usePanelStore } from '@/stores/panel'
import Murri, { Item } from 'muuri'
import CardContainer from '@/views/briefinfo/components/CardContainer.vue'
import 'element-plus/es/components/message/style/css'
import { getEventBus } from '@/common/services/chat-event-bus'
const win: any = window
const { getUrlParams } = win.F10Utils
const { updateViewEventBus } = getEventBus()

const panelStore = usePanelStore()

const pageContainer = ref<HTMLElement | null>(null)

const grid = ref<Murri | null>(null)

const compVmArr = ref<any>([])

const loading = ref(false)

const noData = ref(false)

const gridItemMap: Map<string, Item | undefined> = new Map()

const pageCreator = async (stock: string, ids: string) => {
  loading.value = true
  const section = await getCustomeRender(stock, ids).catch(() => {
    loading.value = false
    noData.value = true
    alert('获取数据失败，请检查参数是否正确')
    throw new Error('获取数据失败')
  })

  const res = {
    sections: [section]
  }
  grid.value = new Murri(pageContainer.value!, {
    items: '.card',
    dragEnabled: false,
    layout: {
      fillGaps: true
    }
  })

  console.log('grid', grid.value)

  // 组件实例创建 & 添加到布局
  if (res && res.sections && res.sections.length) {
    noData.value = false
    await nextTick()
    res.sections.forEach((section) => {
      const el = document.createElement('div')
      const compApp = createApp(CardContainer, { section })
      const compVm = compApp.mount(el)
      compVmArr.value.push(compApp)
      const gridItem = grid.value?.add(compVm.$el)[0]
      gridItemMap.set(section.id, gridItem)
      updateView()
    })
    panelStore.setSections(res.sections)
    loading.value = false
    return
  }
  panelStore.setSections([])
  loading.value = false
  noData.value = true
}

onMounted(() => {
  pageCreator(getUrlParams('stock'), getUrlParams('ids'))
})

function updateView() {
  const cardEleList = grid.value?.getItems()
  grid.value?.refreshItems(cardEleList, true)
  grid.value?.layout()
}

updateViewEventBus.on(() => {
  console.log('updateView')
  updateView()
})
</script>
